import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class NewsDemo extends StatefulWidget {
  NewsDemo({Key key}) : super(key: key);

  @override
  _NewsDemoState createState() => _NewsDemoState();
}

class _NewsDemoState extends State<NewsDemo> {
  List _list = [];
  bool _isLoadingMoreData = false;
  bool _noMoreData = false;
  int _page = 1;
  int _count = 15;
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this._getData();
    this.testFunction(age: 18);
    _scrollController.addListener(() {
      // print(_scrollController.position.pixels);             // 获取滚动条下拉的距离
      // print(_scrollController.position.maxScrollExtent);    // 获取整个页面的高度
      if (_scrollController.position.pixels > _scrollController.position.maxScrollExtent - 40) {
        // print("下拉加载更多");
        if (this._noMoreData) return;
        this._page++;
        this._getData();
      }
    });
  }

  void _getData() async {
    if (this._isLoadingMoreData) return;
    this._isLoadingMoreData = true;
    Response response;
    Dio dio = new Dio();
    response = await dio.post("https://api.apiopen.top/getWangYiNews", queryParameters: {"page": this._page, "count": this._count});
    if (response.data["result"].isEmpty) {
      this._noMoreData = true;
    }
    // print(response);
    setState(() {
      this._list.addAll((response.data)["result"]);
      this._isLoadingMoreData = false;
    });
  }

  void _tapListTile(int index) {
    print(index);
    Navigator.pushNamed(context, '/newscontent', arguments: {"aid": this._list[index]["passtime"]});
  }

  void testFunction({age}) {
    print("age");
    print(age);
  }

  Future _onRefresh() async {
    // 下拉刷新
    print("下拉刷新");
    await Future.delayed(Duration(milliseconds: 2000), () {
      print("数据加载完成");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("新闻头条"),
        ),
        body: this._list.length > 0
            ? RefreshIndicator(
                child: ListView.builder(
                    controller: _scrollController,
                    itemCount: this._list.length,
                    itemBuilder: (BuildContext context, int index) {
                      if (index == 0) {
                        // 这是最后一个ListTile
                        return Column(
                          children: <Widget>[
                            _getMoreWidget(),
                            ListTile(
                                title: Text(
                                  this._list[index]["title"],
                                  maxLines: 1,
                                ),
                                onTap: () {
                                  this._tapListTile(index);
                                }),
                            Divider(),
                          ],
                        );
                      }
                      return Column(
                        children: <Widget>[
                          ListTile(
                              title: Text(
                                this._list[index]["title"],
                                maxLines: 1,
                              ),
                              onTap: () {
                                this._tapListTile(index);
                              }),
                          Divider()
                        ],
                      );
                    }),
                onRefresh: _onRefresh,
              )
            : Text("数据正在加载中"));
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(16.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            CircularProgressIndicator(
              backgroundColor: Colors.amber,
              valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),
              strokeWidth: 3.0,
            ),
            Text(
              "加载中...",
              style: TextStyle(fontSize: 16.0),
            )
          ],
        ),
      ),
    );
  }
}
